package com.jts.cloudspokes.datastore;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.jts.cloudspokes.BotConstants;
import com.jts.cloudspokes.entities.BotTaskEntity;
import com.jts.cloudspokes.util.BotPMF;

public class BotDSManager {
	
	private PersistenceManager botPM = null;
	private final Logger logger = Logger.getLogger(BotDSManager.class.getName());
	private boolean isActive = false; 
	
	public BotDSManager() {
		
	}
	
	public void startPersistenceManager() {
		this.botPM = BotPMF.get().getPersistenceManager();
		isActive = true;
	}
	
	public void stopPersistenceManager() {
		this.botPM.close();
		isActive = false;
	}
	
	@SuppressWarnings("finally")
	public BotTaskEntity fetchTaskFromDSByKey(String taskId) {
		if (!isActive) {
			logger.log(Level.SEVERE, "Persistence Manager is not started");
			return null;
		}
		BotTaskEntity bteObj = null;
		try {
			bteObj = botPM.getObjectById(BotTaskEntity.class, Long.parseLong(taskId));
		} catch (JDOObjectNotFoundException e) {
			e.printStackTrace();
			logger.warning("Error: Not able to find object with id " + taskId);
		} finally {
			return bteObj;			
		}
	}
	
	@SuppressWarnings({ "finally", "unchecked" })
	public List<BotTaskEntity> fetchTasksFromDS(String userId) {
		if (!isActive) {
			logger.log(Level.SEVERE, "Persistence Manager is not started");
			return null;
		}
		List<BotTaskEntity> bteObjs = null;
		Query query = botPM.newQuery(BotTaskEntity.class);
		query.setFilter(BotConstants.PROP_USER_ID + " == emailParam");
		query.declareParameters("String emailParam");
		try {
			bteObjs = (List<BotTaskEntity>) query.execute(userId);
		} catch (Exception e) {
			e.printStackTrace();
			logger.log(Level.SEVERE, e.getMessage());			
		} finally {
			query.closeAll();
			return bteObjs;
		}
	}
	
	@SuppressWarnings({ "finally" })
	public String deleteTask(String userId, String taskId) {
		if (!isActive) {
			logger.log(Level.SEVERE, "Persistence Manager is not started");
			return "Error: Task cannot be deleted";
		}
		logger.info("Task id is " + taskId);
		String response =  BotConstants.STATUS_SUCCESS;
		try {
			List<BotTaskEntity> taskEntities = fetchTasksFromDS(userId);
			if (taskEntities.isEmpty()) {
				response = "Error: Object with id " + taskId + " is not found for user " + userId;
				return response;
			} else {
				for (BotTaskEntity taskEntity : taskEntities) {
					if (taskEntity.getKey() == Long.parseLong(taskId)) {
						botPM.deletePersistentAll(taskEntity);
						break;
					}
				}				
			}
		} catch (Exception e) {
			e.printStackTrace();
			response = "Error: Not able to delete task with id " + taskId;
			logger.log(Level.SEVERE, e.getMessage());
		} finally {
			return response;
		}
	}
	
	@SuppressWarnings("finally")
	public String deleteAllTasks(String userId) {
		if (!isActive) {
			logger.log(Level.SEVERE, "Persistence Manager is not started");
			return "Error: Tasks cannot be deleted";
		}
		String response = BotConstants.STATUS_SUCCESS;
		try {
			List<BotTaskEntity> taskEntities = fetchTasksFromDS(userId);
			if (taskEntities == null || taskEntities.isEmpty()) {
				response = "No tasks available";
			} else {
				botPM.deletePersistentAll(taskEntities);					
			}			
		} catch (Exception e) {
			response = BotConstants.STATUS_ERROR + ": " + e.getMessage();
		} finally {
			return response;
		}
	}
	
	public PersistenceManager getPersistentManager() {
		return botPM;
	}
}
